<template>
    <div class="company-detail" v-loading="loading" element-loading-text="Loading..."
        element-loading-background="rgba(122, 122, 122, 0.1)">
        <el-card class="box-card">
            <template #header>
                <div class="header-left">
                    <el-button link type="primary" :icon="Back" @click="goBack">返回</el-button>
                    <span class="title-divider">|</span>
                    <span class="card-title">公司详情</span>
                </div>
                <div class="header-right">
                    <el-button type="primary" :icon="Edit" size="small" @click="editCompany">
                        编辑
                    </el-button>
                    <el-button type="danger" :icon="Delete" size="small" @click="deleteCompany">
                        删除
                    </el-button>
                </div>
            </template>
            <el-descriptions class="company-info-grid" title="公司信息" :column="4" border>
                <el-descriptions-item label="公司名称">{{ company.name }}</el-descriptions-item>
                <el-descriptions-item label="联系电话">{{ company.phone }}</el-descriptions-item>
                <el-descriptions-item label="状态">
                    <el-tag :type="company.status === 1 ? 'success' : 'danger'" effect="light">
                        {{ company.status === 1 ? '可用' : '不可用' }}
                    </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="行业代码">{{ company.company_code }}</el-descriptions-item>
                <el-descriptions-item label="产品">{{ company.product_name }}</el-descriptions-item>
                <el-descriptions-item label="行业">{{ formatSector(company.sector_id) }}</el-descriptions-item>
                <el-descriptions-item label="省市区">{{ formatLocation(company.location_id) }}</el-descriptions-item>
                <el-descriptions-item label="详细地址">{{ company.location }}</el-descriptions-item>
                <el-descriptions-item label="到期时间">
                    <template v-if="company.expire && formatExpireTime(company.expire) !== '永不到期'">
                        {{ formatExpireTime(company.expire) }}
                    </template>
                    <template v-else>
                        <el-tag type="success">永不到期</el-tag>
                    </template>
                </el-descriptions-item>
                <el-descriptions-item label="备注" :span="4" v-if="company.comment">
                    <el-tooltip class="item" effect="dark" :content="company.comment" placement="top">
                        <span class="ellipsis">{{ company.comment }}</span>
                    </el-tooltip>
                </el-descriptions-item>
            </el-descriptions>
        </el-card>

        <div class="box-card">
            <UserTable :company_id="id" />
        </div>
    </div>

    <el-dialog title="编辑公司" align-center v-model="dialogVisible" :close-on-click-modal="false">
        <CompanyDialog @fetch-company-list="getCompanyDetail" :id="id"></CompanyDialog>
    </el-dialog>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { Edit, Delete, Back } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { deleteCompanyApi, getCompanyListApi } from '@/api/company';
import UserTable from '@/views/SystemManagement/UserManagement/index.vue';
import CompanyDialog from '../CompanyList/components/CompanyDialog.vue';
import { regionData, codeToText } from 'element-china-area-data';
import sector_classification from '@/assets/sector/sector_classification.json';
import dayjs from 'dayjs';

const router = useRouter();
const id = ref(null);
id.value = router.currentRoute.value.query.id


const dialogVisible = ref(false);
const company = ref({});
const loading = ref(true);

// 格式化到期时间
const formatExpireTime = (timestamp) => {
    if (!timestamp || dayjs(timestamp).isBefore(dayjs(2000, 1, 1))) return '永不到期';

    dayjs(timestamp)
    return dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss');
};

// 格式化省市区
const formatLocation = (locationId) => {
    if (!locationId) return '';

    try {
        // locationId 是以逗号分隔的字符串
        const codes = locationId.split(',');
        const locationNames = codes.map(code => codeToText[code]);
        return locationNames.join(' ');
    } catch (error) {

        return locationId;
    }
};

// 格式化行业信息
const formatSector = (sectorId) => {
    if (!sectorId) return '';

    try {
        // 递归查找行业名称
        const findSectorName = (sectorsList, id) => {
            for (const sector of sectorsList) {
                if (sector.value === id) {
                    return sector.label;
                }
                if (sector.children && sector.children.length > 0) {
                    const found = findSectorName(sector.children, id);
                    if (found) return found;
                }
            }
            return null;
        };

        // sectorId 是以逗号分隔的字符串
        const ids = sectorId.split(',');
        const sectorNames = [];

        for (const id of ids) {
            const name = findSectorName(sector_classification, id);
            if (name) sectorNames.push(name);
        }

        return sectorNames.join(' > ');
    } catch (error) {

        return sectorId;
    }
};

// 获取公司详情
function getCompanyDetail() {
    loading.value = true;
    dialogVisible.value = false;
    getCompanyListApi({ id: id.value }).then((res) => {
        if (res.code === 200) {
            company.value = res.data.companies[0];
        } else {
            ElMessage.error(res.message || '获取公司详情失败');
        }
    }).catch((err) => {
        ElMessage.error(err.message || '获取公司详情失败');
    }).finally(() => {
        loading.value = false;
    });
}

onMounted(() => {
    getCompanyDetail();
});

// 返回上级页面
const goBack = () => {
    if (window.history.length > 1) {
        router.back();
    } else {
        router.push('/home/company');
    }
};

const editCompany = () => {
    dialogVisible.value = true;
};

// 删除公司
const deleteCompany = () => {
    ElMessageBox.confirm('确定要删除该公司吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async () => {
        loading.value = true;
        try {
            const res = await deleteCompanyApi({ id: +id.value });
            ElMessage.success('公司删除成功');
            router.push({ name: 'CompanyManagement' })
        } catch (error) {
            ElMessage.error(error.message || '删除公司失败');
        } finally {
            loading.value = false;
        }
    }).catch(() => { });
};
</script>

<style scoped>
.company-detail {
    padding: 1rem;
    min-height: 100%;
}

.box-card {
    width: 100%;
    margin-bottom: 1rem;
}

.box-card :deep(.el-card__header) {
    padding: 1rem;
}

.card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.header-left {
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.header-right {
    display: flex;
    gap: 0.5rem;
}

.title-divider {
    color: #dcdfe6;
    margin: 0 0.5rem;
}

.card-title {
    font-size: 1rem;
    font-weight: 500;
    color: #303133;
}

.header-left :deep(.el-button) {
    font-size: 0.9rem;
}

.header-left :deep(.el-button:hover) {
    opacity: 0.8;
}

.ellipsis {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    display: block;
    max-width: 300px;
}
</style>